package com.zhieasy.filter;

import org.springframework.context.annotation.Bean;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.DefaultCookieSerializer;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局跨域操作
 * @author 风亦未止
 * @date 2021/11/3 19:26
 */
@Component
public class CORSFilter implements Filter {
    private static final String ALLOWED_ORIGIN = "*";
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Credentials", "true");
        res.addHeader("Access-Control-Allow-Origin", ALLOWED_ORIGIN);
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,token,X-TOKEN,Content-Disposition");
        if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
            response.getWriter().println("ok");
            return;
        }
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
    }
    @Override
    public void init(FilterConfig filterConfig){
    }

    /**
     * 携带cookie
     * @return
     */
//    @Bean
//    public CookieSerializer httpSessionIdResolver(){
//        DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer();
//        cookieSerializer.setCookieName("token");
//        cookieSerializer.setUseHttpOnlyCookie(false);
//        cookieSerializer.setSameSite(null);
//        return cookieSerializer;
//    }
}


